﻿using System;
using System.IO;
using System.Linq;
using System.Threading;

namespace Common
{
    public static class Log
    {
        static ReaderWriterLockSlim lockSlim = new ReaderWriterLockSlim();

		/// <summary>
		/// 输出到指定的文件
		/// </summary>
		/// <param name="fileLog"></param>
		/// <param name="str"></param>
        public static void ToFile(string fileLog, string str)
        {
            lockSlim.EnterWriteLock();
            try
            {
                DateTime now = DateTime.Now;
                File.AppendAllText(fileLog, "[" + now.ToString("MMdd HH:mm:ss") + "]" + str + "\r\n");
            }
            catch
            {
                try
                {
                    string[] st = fileLog.Split('\\');
                    string folder = fileLog.Substring(0, fileLog.Length - 1 - st.Last().Length);
                    if (!Directory.Exists(folder))
                    {
                        Directory.CreateDirectory(folder);
                    }
                    DateTime now = DateTime.Now;
                    File.AppendAllText(fileLog, "[" + now.ToString("MMdd HH:mm:ss") + "]" + str + "\r\n");
                }
                catch
                {
                    throw;
                }
            }
            lockSlim.ExitWriteLock();
        }

		/// <summary>
		/// 输出到控制台
		/// </summary>
		/// <param name="str"></param>
        public static void ToConsole(string str)
        {
            if(str == null)
            {
                Console.WriteLine( ":  NULL" );
			}
			else
			{
				DateTime now = DateTime.Now;
				Console.WriteLine("[" + now.ToString("MMdd HH:mm:ss") + "]" + str);
			}
        }
    }
}
